/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.gateway.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.reactive.filter.OrderedWebFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import static com.arisgo.cloud.gateway.utils.ExchangeUtil.sendResponseError;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;
import static org.springframework.http.HttpStatus.NOT_FOUND;

/**
 * 验证url前缀，并去除前缀
 * TODO 测试过程中发现 WebFilter 在 GlobalFilter 之前生效，且WebFilter在适配url前生效，GlobalFilter在适配之后生效
 * 需要再次验证
 *
 * @author Arisgo
 * @since 2024/6/3
 */
@Configuration
public class RequestFilter implements OrderedWebFilter {

    @Value(value = "${arisgo.cloud.url.prefix:gateway}")
    private String prefix;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        addOriginalRequestUrl(exchange, request.getURI());
        String path = request.getURI().getRawPath();

        // 验证前缀
        if (!path.startsWith(prefix)) {
            return sendResponseError(exchange, NOT_FOUND);
        }

        ServerHttpRequest newRequest = request.mutate().path(path.replaceFirst(prefix, "")).build();
        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
        return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
